<template>
  <div class="borrow-container">
    <!-- 标签页切换 -->
    <div class="tabs-container neu-card">
      <div class="tabs-header">
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'borrow' }" 
          @click="activeTab = 'borrow'"
        >
          借阅管理
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === 'records' }" 
          @click="activeTab = 'records'"
        >
          借阅记录
        </div>
      </div>
      
      <!-- 借阅管理标签页 -->
      <div v-if="activeTab === 'borrow'" class="tab-content">
        <div class="search-section">
          <div class="search-input">
            <input 
              type="text" 
              v-model="searchQuery" 
              class="neu-input" 
              placeholder="搜索图书名称、ISBN或作者"
              @keyup.enter="searchBooks"
            />
            <button class="neu-button primary" @click="searchBooks">
              <el-icon><Search /></el-icon>
              搜索
            </button>
          </div>
        </div>
        
        <!-- 可借阅图书列表 -->
        <div class="books-list">
          <h3>可借阅图书</h3>
          <el-table 
            :data="availableBooks" 
            style="width: 100%" 
            v-loading="loading"
            class="neu-table-wrapper"
          >
            <el-table-column prop="title" label="书名" min-width="150" />
            <el-table-column prop="author" label="作者" min-width="120" />
            <el-table-column prop="publisher" label="出版社" min-width="150" />
            <el-table-column prop="category" label="分类" width="100" />
            <el-table-column prop="location" label="馆藏位置" min-width="120" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <button class="borrow-btn" @click="showBorrowDialog(scope.row)">
                  <el-icon><TopRight /></el-icon>
                  借阅
                </button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      
      <!-- 借阅记录标签页 -->
      <div v-if="activeTab === 'records'" class="tab-content">
        <div class="filter-section">
          <div class="filter-options">
            <div class="filter-item">
              <label>状态</label>
              <el-select v-model="recordStatus" placeholder="全部状态" @change="fetchBorrowRecords">
                <el-option label="全部状态" value="" />
                <el-option label="借出" value="借出" />
                <el-option label="已还" value="已还" />
              </el-select>
            </div>
          </div>
        </div>
        
        <!-- 借阅记录列表 -->
        <div class="records-list">
          <h3>借阅记录</h3>
          <el-table 
            :data="borrowRecords" 
            style="width: 100%" 
            v-loading="recordsLoading"
            class="neu-table-wrapper"
          >
            <el-table-column prop="bookTitle" label="书名" min-width="150" />
            <el-table-column prop="borrowDate" label="借阅日期" width="120" />
            <el-table-column prop="returnDate" label="归还日期" width="120">
              <template #default="scope">
                {{ scope.row.returnDate || '未归还' }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <span 
                  class="status-tag" 
                  :class="scope.row.status === '已还' ? 'returned' : 'borrowed'"
                >
                  {{ scope.row.status }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <button 
                  v-if="scope.row.status === '借出'" 
                  class="return-btn" 
                  @click="showReturnDialog(scope.row)"
                >
                  <el-icon><BottomLeft /></el-icon>
                  归还
                </button>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="recordsCurrentPage"
              v-model:page-size="recordsPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordsTotal"
              @size-change="handleRecordsSizeChange"
              @current-change="handleRecordsCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 借阅确认对话框 -->
    <el-dialog
      v-model="borrowDialogVisible"
      title="借阅确认"
      width="400px"
      class="neu-dialog"
    >
      <div class="borrow-dialog-content">
        <p>确认借阅《{{ selectedBook?.title }}》？</p>
        <p class="book-info">作者：{{ selectedBook?.author }}</p>
        <p class="book-info">出版社：{{ selectedBook?.publisher }}</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="neu-button" @click="borrowDialogVisible = false">取消</button>
          <button class="neu-button primary" @click="confirmBorrow">确认借阅</button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 归还确认对话框 -->
    <el-dialog
      v-model="returnDialogVisible"
      title="归还确认"
      width="400px"
      class="neu-dialog"
    >
      <div class="return-dialog-content">
        <p>确认归还《{{ selectedRecord?.bookTitle }}》？</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="neu-button" @click="returnDialogVisible = false">取消</button>
          <button class="neu-button primary" @click="confirmReturn">确认归还</button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, TopRight, BottomLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { borrowService } from '../api/services'

// 标签页状态
const activeTab = ref('borrow')

// 搜索和筛选
const searchQuery = ref('')
const recordStatus = ref('')

// 分页参数 - 可借阅图书
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页参数 - 借阅记录
const recordsCurrentPage = ref(1)
const recordsPageSize = ref(10)
const recordsTotal = ref(0)

// 数据列表
const availableBooks = ref([])
const borrowRecords = ref([])

// 加载状态
const loading = ref(false)
const recordsLoading = ref(false)

// 对话框状态
const borrowDialogVisible = ref(false)
const returnDialogVisible = ref(false)
const selectedBook = ref(null)
const selectedRecord = ref(null)

// 获取可借阅图书列表
const fetchAvailableBooks = async () => {
  try {
    loading.value = true
    const response = await borrowService.getAvailableBooks({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value
    })
    
    if (response.code === 200) {
      availableBooks.value = response.data.list
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取可借阅图书失败:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 获取借阅记录
const fetchBorrowRecords = async () => {
  try {
    recordsLoading.value = true
    const response = await borrowService.getBorrowRecords({
      page: recordsCurrentPage.value,
      pageSize: recordsPageSize.value,
      status: recordStatus.value
    })
    
    if (response.code === 200) {
      borrowRecords.value = response.data.list
      recordsTotal.value = response.data.total
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
  } finally {
    recordsLoading.value = false
  }
}

// 搜索图书
const searchBooks = () => {
  currentPage.value = 1
  fetchAvailableBooks()
}

// 显示借阅对话框
const showBorrowDialog = (book) => {
  selectedBook.value = book
  borrowDialogVisible.value = true
}

// 确认借阅
const confirmBorrow = async () => {
  try {
    const response = await borrowService.borrowBook(selectedBook.value.id)
    if (response.code === 200) {
      ElMessage.success('借阅成功')
      borrowDialogVisible.value = false
      fetchAvailableBooks()
      if (activeTab.value === 'records') {
        fetchBorrowRecords()
      }
    } else {
      ElMessage.error(response.message || '借阅失败')
    }
  } catch (error) {
    console.error('借阅失败:', error)
    ElMessage.error('借阅失败')
  }
}

// 显示归还对话框
const showReturnDialog = (record) => {
  selectedRecord.value = record
  returnDialogVisible.value = true
}

// 确认归还
const confirmReturn = async () => {
  try {
    const response = await borrowService.returnBook(selectedRecord.value.id)
    if (response.code === 200) {
      ElMessage.success('归还成功')
      returnDialogVisible.value = false
      fetchBorrowRecords()
    } else {
      ElMessage.error(response.message || '归还失败')
    }
  } catch (error) {
    console.error('归还失败:', error)
    ElMessage.error('归还失败')
  }
}

// 分页处理 - 可借阅图书
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAvailableBooks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAvailableBooks()
}

// 分页处理 - 借阅记录
const handleRecordsSizeChange = (val) => {
  recordsPageSize.value = val
  fetchBorrowRecords()
}

const handleRecordsCurrentChange = (val) => {
  recordsCurrentPage.value = val
  fetchBorrowRecords()
}

// 初始化
onMounted(() => {
  fetchAvailableBooks()
  fetchBorrowRecords()
})
</script>

<style scoped>
@import '../assets/styles/neumorphism.css';

.borrow-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tabs-container {
  padding: 20px;
}

.tabs-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  border-radius: 8px;
  color: var(--text-secondary);
  transition: all 0.3s ease;
}

.tab-item:hover {
  color: var(--primary-blue);
}

.tab-item.active {
  color: var(--primary-blue);
  font-weight: 500;
  box-shadow: var(--inner-shadow);
}

.search-section {
  margin-bottom: 20px;
}

.search-input {
  display: flex;
  gap: 10px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-options {
  display: flex;
  gap: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.books-list,
.records-list {
  margin-top: 20px;
}

.books-list h3,
.records-list h3 {
  margin-bottom: 15px;
  color: var(--text-primary);
}

.borrow-btn,
.return-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.borrow-btn {
  background-color: var(--primary-green-light);
  color: var(--primary-green);
}

.return-btn {
  background-color: var(--primary-blue-light);
  color: var(--primary-blue);
}

.borrow-btn:hover {
  background-color: var(--primary-green);
  color: white;
}

.return-btn:hover {
  background-color: var(--primary-blue);
  color: white;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-tag.borrowed {
  background-color: var(--primary-blue-light);
  color: var(--primary-blue);
}

.status-tag.returned {
  background-color: var(--success-light);
  color: var(--success);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.book-info {
  color: var(--text-secondary);
  margin: 5px 0;
}
</style>